﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using HtmlAgilityPack;
using System.Net;
using System.IO;

namespace ApplicationBll
{
    public class Stock
    {
        private AccessSQL asql = new AccessSQL();

        /// <summary>
        /// 获取股票信息
        /// </summary>
        /// <param name="codePre">代码前缀，sh或sz</param>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public string GetJSONStockInfo(string codePre, int start, int limit) 
        {
            string sql = string.Format("select code from stock where Code LIKE '{0}%' ORDER BY Code", codePre);
            if (codePre == "my")
            {
                //自选股
                sql = "select code from stock where IsMy = true ORDER BY Code";
            }

            DataTable table = asql.GetDataTable(sql);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < limit && start < table.Rows.Count; i++)
            {
                sb.Append(table.Rows[start++]["code"] + ",");
            }
            sb.Remove(sb.Length-1, 1);
            string url = "http://hq.sinajs.cn/list=" + sb.ToString();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse rp = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(rp.GetResponseStream(), Encoding.GetEncoding("GBK"));
            string info = sr.ReadLine();
            StringBuilder sbInfo = new StringBuilder();
            while (info != null)
            {
                
                string []infos = info.Substring(info.IndexOf("\"") + 1, info.LastIndexOf("\"") - info.IndexOf("\"") - 1).Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries);
                string code = info.Substring(11, 8);
                sbInfo.Append("{");
                sbInfo.Append(string.Format("code:'{0}',name:'{1}',open:'{2}',close:'{3}',price:'{4}',max:'{5}',min:'{6}',cj:'{7}',cjj:'{8}',time:'{9}'", code, infos[0], infos[1], infos[2], infos[3], infos[4], infos[5], int.Parse(infos[8]) / 100, float.Parse(infos[9]) / 10000, infos[30] + infos[31]));
                sbInfo.Append("},");

                info = sr.ReadLine();
            }
            sr.Close();
            sbInfo.Remove(sbInfo.Length - 1, 1);
            string json = string.Format("count:{0},rows:[{1}]", table.Rows.Count, sbInfo);
            return "{"+json+"}";
        }
        /// <summary>
        /// 验证股票代码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool ValidateStockCode(string code)
        {
            code = SetCode(code);
            if (code.Length == 8)
            {
                string sql = string.Format("select count(1) from stock where code = '{0}'", code);
                return asql.ExecuteScalar(sql).ToString() == "1";
            }
            else {
                return false;
            }
        }
        /// <summary>
        /// 添加自选股
        /// </summary>
        /// <param name="code"></param>
        public int AddMyStockInfo(string code)
        {
            code = SetCode(code);
            string sql = string.Format("UPDATE Stock SET IsMy = true WHERE (Code = '{0}')", code);
            return asql.ExecuteNonQuery(sql);
        }
        /// <summary>
        /// 删除自选股
        /// </summary>
        /// <param name="code"></param>
        public int RemoveMyStockInfo(string code)
        {
            
            string sql = string.Format("UPDATE Stock SET IsMy = false WHERE Code in ({0})", code);
            return asql.ExecuteNonQuery(sql);
        }

        private static string SetCode(string code)
        {
            if (code.Length == 6)
            {
                code = code.StartsWith("0") ? "sz" + code : "sh" + code;
            }
            return code;
        }
    }
}
